package com.allwayz.controller;

import com.allwayz.entity.CommonResult;
import com.allwayz.entity.Payment;
import com.allwayz.lb.LoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @author allwayz
 */
@RestController
@RequestMapping("order")
public class OrderController {
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE/";
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private LoadBalancer loadBalancer;
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("payment/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable String id){
        return restTemplate.getForObject(PAYMENT_URL+"payment/"+id, CommonResult.class);
    }

    @GetMapping("payment")
    public CommonResult<Payment> createPayment(Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"payment",payment,CommonResult.class);
    }

    @GetMapping("payment/entity/{id}")
    public CommonResult<Payment> getPaymentByEntity(@PathVariable String id){
        ResponseEntity<CommonResult> resultResponseEntity = restTemplate.getForEntity(PAYMENT_URL+"payment/"+id,CommonResult.class);
        if(resultResponseEntity.getStatusCode().is2xxSuccessful()){
            return resultResponseEntity.getBody();
        }else {
            return new CommonResult<>(444,"操作失败");
        }
    }

    @GetMapping("payment/lb")
    public String getPaymentLoadBalance(){
        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if(serviceInstanceList == null || serviceInstanceList.size()<=0){
            return null;
        }
        ServiceInstance serviceInstance = loadBalancer.serviceInstance(serviceInstanceList);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri+"payment/lb",String.class);
    }

    @GetMapping("zipkin")
    public String paymentZipkin(){
        String result = restTemplate.getForObject("http://localhost:8001/"+"payment/zipkin",String.class);
        return result;
    }
}

